﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using cszmcaux;
using static cszmcaux.Zmcaux;
using Zmotion406.Models;
using static System.Runtime.InteropServices.JavaScript.JSType;
using Newtonsoft.Json;

namespace Zmotion406.Service
{
    public class ConfigService
    {
        /// <summary>
        /// 获取串口
        /// </summary>
        /// <returns>IP列表</returns>
        public static List<string> GetSerialPort()
        {
            List<string> list = new List<string>();
            var buffer = new StringBuilder();
            int res = ZAux_SearchEthlist(buffer, 1024, 1000);
            if(res != 0)
            {
                MessageBox.Show("IP地址扫描出错！");
                return list;
            }
            var ips = buffer.ToString().Split(" ");
            list.AddRange(ips.Where(ip=> !string.IsNullOrWhiteSpace(ip)));
            list.Add("127.0.0.1");
            return list;
        }
        /// <summary>
        /// 连接控制器
        /// </summary>
        /// <param name="ip"></param>
        /// <returns>返回状态：1成功，0失败</returns>
        public static int ConnectEquipment(string ip)
        {
            IntPtr handle;
            int res = ZAux_OpenEth(ip, out handle);
            if(res != 0)
            {
                MessageBox.Show("连接串口失败！");
                return 0;
            }
            ConfigModel.Handle = handle;
            return 1;
        }
        /// <summary>
        /// 断开连接
        /// </summary>
        /// <returns>返回状态：1成功，0失败</returns>
        public static int CloseConnect()
        {
            if(ConfigModel.Handle != IntPtr.Zero)
            {
                int res = ZAux_Close(ConfigModel.Handle);
                if(res == 0)
                {
                    return 1;
                }
            }
            return 0;
        }
        /// <summary>
        /// 序列化保存当前轴配置信息
        /// </summary>
        /// <param name="AxleNumber"></param>
        /// <param name="axis"></param>
        /// <returns></returns>
        public static int SaveAxis(int AxleNumber, AxisModel axis)
        {
            try
            {
                ConfigModel.Allaxis[AxleNumber] = axis;
                string json = JsonConvert.SerializeObject(ConfigModel.Allaxis);
                File.WriteAllText("axis.json", json);
                MessageBox.Show("保存成功！");
                return 1;
            }
            catch (JsonSerializationException jex)
            {
                // 处理JSON序列化相关的异常
                MessageBox.Show($"保存失败: JSON序列化错误 - {jex.Message}");
            }
            catch (IOException ioex)
            {
                // 处理文件IO相关的异常
                MessageBox.Show($"保存失败: 文件IO错误 - {ioex.Message}");
            }
            catch (UnauthorizedAccessException uaex)
            {
                // 处理权限相关的异常
                MessageBox.Show($"保存失败: 权限不足 - {uaex.Message}");
            }
            catch (Exception ex)
            {
                // 捕获所有其他类型的异常
                MessageBox.Show($"保存失败: 其他错误 - {ex.Message}");
            }
            return 0;
        }
        /// <summary>
        /// 序列化保存全部轴配置信息
        /// </summary>
        /// <param name="axis"></param>
        /// <returns>状态</returns>
        public static int SaveAllAxis(AxisModel axis)
        {
            try
            {
                ConfigModel.Allaxis[1] = axis;
                ConfigModel.Allaxis[2] = axis;
                ConfigModel.Allaxis[3] = axis;
                ConfigModel.Allaxis[4] = axis;
                string json = JsonConvert.SerializeObject(ConfigModel.Allaxis);
                File.WriteAllText("axis.json", json);
                MessageBox.Show("全部保存成功！");
                return 1;
            }
            catch (JsonSerializationException jex)
            {
                // 处理JSON序列化相关的异常
                MessageBox.Show($"保存失败: JSON序列化错误 - {jex.Message}");
            }
            catch (IOException ioex)
            {
                // 处理文件IO相关的异常
                MessageBox.Show($"保存失败: 文件IO错误 - {ioex.Message}");
            }
            catch (UnauthorizedAccessException uaex)
            {
                // 处理权限相关的异常
                MessageBox.Show($"保存失败: 权限不足 - {uaex.Message}");
            }
            catch (Exception ex)
            {
                // 捕获所有其他类型的异常
                MessageBox.Show($"保存失败: 其他错误 - {ex.Message}");
            }
            return 0;
        }
        /// <summary>
        /// 获取各轴序列化参数
        /// </summary>
        public static void GetJsonAxisConfig()
        {
            try
            {
                string readJsonString  = File.ReadAllText("axis.json");
                Dictionary<int,AxisModel>?  Allaxis = JsonConvert.DeserializeObject<Dictionary<int, AxisModel>>(readJsonString);
                if (Allaxis!= null){
                    ConfigModel.Allaxis = Allaxis;
                }

            }
            catch (FileNotFoundException ex)
            {
                // 处理文件未找到的异常
                Console.WriteLine($"无法找到指定的文件: {ex.Message}");
            }
            catch (JsonReaderException ex)
            {
                // 处理解析JSON时发生的异常
                Console.WriteLine($"JSON解析错误: {ex.Message}");
            }
            catch (Exception ex)
            {
                // 处理其他任何可能发生的异常
                Console.WriteLine($"发生了一个错误: {ex.Message}");
            }
        }
    }
}
